/*
 * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.orientechnologies.orient.test.database.auto;

import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseSession;
import org.testng.Assert;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

@Test
public class ConcurrentCommandAndOpenTest extends DocumentDBBaseTest {
  protected static final int MAX_CONNS = 10;

  @Parameters(value = "url")
  public ConcurrentCommandAndOpenTest(@Optional String url) {
    super(url);
  }

  @Test
  public void concurrentCommands() throws Exception {
    OGlobalConfiguration.DB_POOL_MIN.setValue(1);
    OGlobalConfiguration.DB_POOL_MAX.setValue(MAX_CONNS);

    final Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try (ODatabaseSession db = openSession("admin", "admin")) {
                  // System.out.println("Start sleeping...");
                  db.execute("SQL", "sleep 5000").close();
                  // System.out.println("Sleeping done!");
                }
              }
            },
            "Test long sleep");

    thread.start();

    Thread.sleep(1000);

    int commandExecuted = 0;
    int iterations = MAX_CONNS * 5;
    for (int i = 0; i < iterations; ++i) {
      // System.out.println("Open database " + i);
      try (ODatabaseSession db = openSession("admin", "admin")) {
        db.command("select from OUser").close();
        // System.out.println("Command executed " + i);
        commandExecuted++;
      }
    }

    // System.out.println("Waiting for the sleeping thread...");
    thread.join();
    // System.out.println("Done!");

    Assert.assertEquals(commandExecuted, iterations);
  }
}
